package net.src.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * 发送端
 */
public class ClientDemo {
    public static void main(String[] args) throws Exception {
        //创建发送端对象,发送端自带端口号
        DatagramSocket socket = new DatagramSocket();

        //创建一个数据包封装数据文件
        /**
         * public DatagramPacket(byte buf[], int length,InetAddress address, int port)
         * 参数一:需要封装的数据(字节数组)
         * 参数二:发送数据的大小
         * 参数三:服务端的ip
         * 参数四:服务端的端口
         */
        byte[] buffer = "这是发送的数据".getBytes();
        byte[] buffer2 = "这是一条广播信息".getBytes();
        DatagramPacket packet = new DatagramPacket(buffer,buffer.length, InetAddress.getLocalHost(),8888);
        //将发送ip切换为4个255,且端口指定为9999,就可以发送广播,在同网段的设备可以接收到
        DatagramPacket board = new DatagramPacket(buffer2,buffer2.length, InetAddress.getByName("255.255.255.255"),9999);

        //发送数据
        socket.send(packet);
        socket.send(board);

        socket.close();
    }
}
